/**
 * Copyright (C), 2020, Y2 T205
 * FileName: indesController
 * Author: Lenovo
 * Date: 2020-05-25 16:25
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */


package com.atguigu.gulimall.gulimallauth.controller;


import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;

import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauth.feign.MemberFeingService;
import com.atguigu.gulimall.gulimallauth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.gulimallauth.vo.UserLoginVo;
import com.atguigu.gulimall.gulimallauth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Lenovo
 * @create 2020-05-25
 * @since 1.0.0
 */

@Controller
public class LoginController {

@Autowired
ThirdPartFeignService thirdPartFeignService;

@Autowired
    StringRedisTemplate redisTemplate;


@Autowired
MemberFeingService memberFeingService;
    /*
    * 发送一个请求直接跳转到一个页面
    * SpringMvc viewcontroller;将请求和页面映射过来
    *
    * */
    /*使用视图解析的方式跳转页面*/
/*    @GetMapping("/login.html")
    public String loginPage(){
        return  "login";
    }

    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }*/
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone")String phone){
       // String code = UUID.randomUUID().toString().substring(0, 5);
        //接口防刷
        String redisCode =redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);

/*        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
//            60秒内不能发送
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }



//        2.验证码的再次校验
        String code = String.valueOf(Math.round((Math.random()+1) * 1000))+"_"+System.currentTimeMillis();*/
        String code = String.valueOf(Math.round((Math.random()+1) * 1000));
//        redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
        return  R.ok();
    }


    @PostMapping("/regist")
    public String regist(UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session){
//          注册成功回到首页
//        校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());

     /*       if(code.equals(s.split("-")[0])){
//                删除验证码
               */
//                验证通过  调用远程服务进行注册
              R r=memberFeingService.regist(vo);
              if(r.getCode()==0){
                  //成功
                  return "redirect:http://auth.gulimall.com/login.html";
              }else{
                  return "redirect:http://auth.gulimall.com/reg.html";
              }
           /* }else{
                Map<String,Object> errors=new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }*/
        }else{
            Map<String,Object> errors=new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
//            校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }


    }

    @GetMapping("/login.html")
    public String login(HttpSession session){
        Object attribute =session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null){
//            没登录
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }

    }



    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
//        远程登录
        R login1 =memberFeingService.login(vo);
        if(login1.getCode()==0){
//            成功
            MemberRespVo data = login1.getData("data", new TypeReference<MemberRespVo>(){});
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else{
            Map<String,String > errors =new HashMap<>();
            errors.put("msg",login1.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }



    }


}
